var http = require('http');
var querystring = require('querystring');
var fs = require('fs');
var url = require('url');
var child_process = require('child_process');
var util = require('util');

var port = 8888;

http.createServer(function(request, response){

    console.log('Servering for '
        + request.connection.remoteAddress
        + ' at ' + new Date());
        

    var post = '';

    request.on('data', function(chunk) {
        post += chunk;
    });

    request.on('end', function() {
        post = querystring.parse(post);
        console.log(post);
        if(post.hook) {
            var hook = JSON.parse(post.hook);
            process(hook);
        } else {
            close("禁止");
        }
    });

    function close(message) {
        response.end(message);
        console.log(message);
    }

    function process(hook) {
        var config = fs.readFileSync('config.json').toString();
        config = JSON.parse(config);
        config.cgiBase = config.cgiBase || "cgi";

        if(hook.password.trim() !== config.password.trim()) {
            close("密码错误");
        } else if(hook.hook_name !== 'push_hooks') {
            close("仅支持PUSH HOOK");
        } else {
            var path = url.parse(request.url).pathname
            var script = config.cgiBase + path;
            child_process.exec(script);
            close("请求成功");
        }
    }
}).listen(port);

console.log(new Date() + ': Server started at :' + port);
